import { createApp, h, ref, type App } from 'vue'
import Modal from '../components/ViModal.vue'

export interface ModalOptions {
  onConfirm?: () => void
  onCancel?: () => void
  title?: string
  content?: string
  showCancel?: boolean
  width?: string | number
  height?: string | number
  slots?: Record<string, any>
}
export interface ModalService {
  (options: ModalOptions): void
  confirm(content: string, title?: string, onConfirm?: () => void, onCancel?: () => void): void
  alert(content: string, title?: string, onConfirm?: () => void): void
  closeAll(): void
}

export function createModal(): ModalService {
  // 全局实例存储
  const instances: App<Element>[] = []
  function modal(options: ModalOptions) {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const visible = ref(true)

    const app = createApp({
      setup() {
        const onClose = () => {
          visible.value = false
          setTimeout(() => {
            app.unmount()
            container.remove()
            const index = instances.findIndex((instance) => instance === app)
            if (index !== -1) {
              instances.splice(index, 1)
            }
          }, 300) // 给过渡动画留时间
        }

        return () =>
          h(
            Modal,
            {
              modelValue: visible.value,
              'onUpdate:modelValue': (val) => {
                visible.value = val
                if (!val) onClose()
              },
              onConfirm: () => {
                if (options.onConfirm) options.onConfirm()
                onClose()
              },
              onCancel: () => {
                if (options.onCancel) options.onCancel()
                onClose()
              },
              ...options,
            },
            options.slots || {},
          )
      },
    })

    instances.push(app)
    app.mount(container)

    return {
      close: () => {
        visible.value = false
      },
    }
  }

  // 预设类型
  modal.alert = (content: string, title = '提示', onConfirm: () => void) => {
    return modal({
      title,
      content,
      showCancel: false,
      onConfirm,
    })
  }

  modal.confirm = (
    content: string,
    title = '确认',
    onConfirm: () => void,
    onCancel: () => void,
  ) => {
    return modal({
      title,
      content,
      onConfirm,
      onCancel,
    })
  }

  // 关闭所有弹窗
  modal.closeAll = () => {
    instances.forEach((instance) => {
      const closeFn = instance._instance?.exposed?.close
      if (typeof closeFn === 'function') {
        closeFn()
      }
    })
  }
  return modal
}

export default {
  install(app: App<Element>) {
    const modal = createModal()
    app.config.globalProperties.$modal = modal
    app.provide('modal', modal)
  },
}
